package it.polimi.swKnights.SWIMv2.ejb.administration;

import it.polimi.swKnights.SWIMv2.ejb.authentication.LoginHandlerLocal;
import it.polimi.swKnights.SWIMv2.ejb.entityBeans.Ability;
import it.polimi.swKnights.SWIMv2.ejb.entityBeans.Admin;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.InvalidLoginPrivilegesException;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.LoginFailException;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 * Session Bean implementation class AbilityToApprove
 */
@Stateless
public class AbilityToApprove implements AbilityToApproveRemote
{

	@PersistenceContext(unitName = "swimv2-manager")
	private EntityManager manager;

	@EJB
	private LoginHandlerLocal loginController;

	@Override
	public Map<String, String> getAbilityToApprove(String admin, String password)
	{
		Map<String, String> ablitiesToApprove = new HashMap<String, String>();
		try
		{
			this.loginController.checkLoginDataAndPrivileges(admin, password,
					Admin.class);

			Query q = manager.createQuery("FROM Ability a "
					+ "WHERE a.alreadySeen='true'");

			List<?> queryList = q.getResultList();

			for (Object item : queryList)
			{
				Ability  ability = (Ability) item;
				ablitiesToApprove.put(ability.getName(), ability.getDescription());
			}
		}
		catch (LoginFailException e)
		{
		}
		catch (InvalidLoginPrivilegesException e)
		{
		}

		return ablitiesToApprove;
	}

	@Override
	public void getAndProcessSeenAbilities(
			Map<String, Boolean> mapAbilitySeenOrNot)
	{
		/*
		 * foreach ability in mapKeys if mapAbility.value == true, that is
		 * approved set Abilty (table) . alreadySeen to 1 (true) set Ability
		 * (table) . approved to 1 (true)
		 * 
		 * else, that is NOT approved
		 * 
		 * set Abilty (table) . alreadySeen to 1 (true) set Ability (table) .
		 * approved to 0 (false)
		 */

		for (Map.Entry<String, Boolean> e : mapAbilitySeenOrNot.entrySet())

		{
			String abilityName = e.getKey();
			Boolean approved = e.getValue();
			Ability abilitySeen = manager.find(Ability.class, abilityName);

			abilitySeen.setAlreadySeen(true);
			if (approved == true)
			{
				abilitySeen.setConfirmed(true);
			}
			else
			{
				abilitySeen.setConfirmed(false);
			}
			manager.persist(abilitySeen);
		}

	}

}
